﻿using IOA.MES.Business;
using IOA.MES.DataAccess.Enum;
using IOA.MES.DataAccess.VModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Web.Mvc;

namespace IOA.MES.Web.Controllers
{
    /// <summary>
    /// 质量
    /// </summary>
    public class QualityController : Controller
    {
        #region 降级复判
        /// <summary>
        /// 降级复判管理
        /// </summary>
        public ActionResult DowngradeMgr()
        {
            ViewBag.Workshops = new WorkshopMgr().QueryUserWorkshops(BaseEnv.UserId);
            ViewBag.ReviewStatusEnum = new CommonMgr().QueryEnumTypes(typeof(ReviewResult));
            return View();
        }

        /// <summary>
        /// 查询降级复判列表
        /// </summary>
        [HttpPost]
        public JsonResult QueryDowngrades(int page, int limit, string workshopCode, string orderNo, string workOrderNo, string barCode,
            DateTime startDate, DateTime endDate, bool? reviewed)
        {
            var total = 0;
            var models = new DowngradeMgr().QueryDowngrades(page, limit, out total, workshopCode, orderNo, workOrderNo, barCode, startDate, endDate.AddDays(1), reviewed);
            return Json(new ResultJson<object>(models, total));
        }

        /// <summary>
        /// 复判页面
        /// </summary>
        public ActionResult Review(int downgradeId)
        {
            var model = new DowngradeMgr().GetDowngrade(downgradeId);
            ViewBag.ReviewStatusEnum = new CommonMgr().QueryEnumTypes(typeof(ReviewResult));
            ViewBag.QLevels = new LevelColorMgr().QueryLevels().Select(_ => _.Level).ToList();
            var total = 0;
            ViewBag.BadReasons = new BadReasonMgr().QueryReasons(1, 0, out total, "", "");
            return View(model);
        }

        /// <summary>
        /// 复判
        /// </summary>
        [HttpPost]
        public JsonResult Review(int downgradeId, string level, string reviewCode)
        {
            new DowngradeMgr().Review(new VDowngrade
            {
                PkId = downgradeId,
                ReviewedBy = BaseEnv.UserId,
                ReviewLevel = level,
                ReviewBadCode = reviewCode,
                ModifyBy = BaseEnv.UserId
            });
            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 批量降级
        /// </summary>
        /// <returns></returns>
        public ActionResult BatchDowngrade()
        {
            ViewBag.QLevels = new LevelColorMgr().QueryLevels();
            ViewBag.SiteTypes = new CommonMgr().QueryEnumTypes(typeof(SiteType));
            var total = 0;
            ViewBag.BadReasons = new BadReasonMgr().QueryReasons(1, 0, out total, "", "");
            return View();
        }

        /// <summary>
        /// 批量降级
        /// </summary>
        [HttpPost]
        public JsonResult BatchDowngrade(List<string> barCodes, List<string> badCodes, SiteType curSite, string level)
        {
            new DowngradeMgr().Downgrade(barCodes ?? new List<string>(), badCodes ?? new List<string>(), curSite, level, BaseEnv.UserId);
            return Json(new ResultJson<object>());
        }
        //导出降级复判清单
        /*
         public JsonResult QueryDowngrades(string workshopCode, string orderNo, string workOrderNo, string barCode,
            DateTime startDate, DateTime endDate, bool? reviewed)
        {
            var total = 0;
            var models = new DowngradeMgr().QueryDowngrades( workshopCode, orderNo, workOrderNo, barCode, startDate, endDate.AddDays(1), reviewed);
            return Json(new ResultJson<object>(models, total));
        }
         */
        public void ExportDowngradeReports(string workshopCode, string orderNo, string workOrderNo, string barCode,
            DateTime startDate, DateTime endDate, bool? reviewed)
        {
            
            var report = new DowngradeMgr().QueryDowngrades(workshopCode, orderNo, workOrderNo, barCode, startDate, endDate.AddDays(1), reviewed);

            var book = new XSSFWorkbook();
            var sheet = book.CreateSheet("降级复判");
            for (int i = 0; i < 33; i++)
            {
                sheet.SetColumnWidth(i, 8 * 256 + 200);
            }
            sheet.SetColumnWidth(0, 8 * 800 + 200);
            sheet.SetColumnWidth(7, 8 * 400 + 200);
            sheet.SetColumnWidth(9, 8 * 400 + 200);
            sheet.SetColumnWidth(10, 8 * 400 + 200);
            sheet.SetColumnWidth(14, 8 * 400 + 200);
            sheet.SetColumnWidth(15, 8 * 400 + 200);
            sheet.SetColumnWidth(18, 8 * 400 + 200);
            sheet.SetColumnWidth(19, 8 * 500 + 200);
            sheet.SetColumnWidth(20, 8 * 300 + 200);
            sheet.SetColumnWidth(23, 8 * 300 + 200);
            sheet.SetColumnWidth(234, 8 * 300 + 200);

            var styleCenter = book.CreateCellStyle();
            styleCenter.Alignment = HorizontalAlignment.Center;
            styleCenter.VerticalAlignment = VerticalAlignment.Center;
            styleCenter.BorderBottom = BorderStyle.Thin;
            styleCenter.BorderLeft = BorderStyle.Thin;
            styleCenter.BorderRight = BorderStyle.Thin;
            styleCenter.BorderTop = BorderStyle.Thin;

            var row1 = sheet.CreateRow(0);
            row1.Height = 30 * 20;
            row1.CreateCell(0).SetCellValue("OrderNo");
            row1.CreateCell(1).SetCellValue("WorkOrderNo");
            row1.CreateCell(2).SetCellValue("WorkshopName");
            row1.CreateCell(3).SetCellValue("BarCode");
            row1.CreateCell(4).SetCellValue("ProductName");
            row1.CreateCell(5).SetCellValue("CurSite");
            row1.CreateCell(6).SetCellValue("Reviewed");
            row1.CreateCell(7).SetCellValue("ReviewedBy");
            row1.CreateCell(8).SetCellValue("QLevel");
            row1.CreateCell(9).SetCellValue("ReviewLevel");
            row1.CreateCell(10).SetCellValue("DowngradeBadTypeName");
            row1.CreateCell(11).SetCellValue("DowngradeBadName");
            row1.CreateCell(12).SetCellValue("ReviewBadTypeName");
            row1.CreateCell(13).SetCellValue("ReviewBadName");           
            for (int i = 0; i <= 14; i++)
            {
                row1.GetCell(i).CellStyle = styleCenter;
            }

            if (!report.Any())
            {
                var ms1 = new MemoryStream();
                book.Write(ms1);
                Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xlsx", $"降级复判（{startDate:yyyyMMddHHmm}-{endDate:yyyyMMddHHmm}）"));
                Response.BinaryWrite(ms1.ToArray());
                book = null;
                ms1.Close();
                ms1.Dispose();
                return;
            }
            for (int i = 0; i < report.Count; i++)
            {
                var tmpRow = sheet.CreateRow(i + 1);
                tmpRow.Height = 30 * 20;
                tmpRow.CreateCell(0).SetCellValue(report[i].OrderNo);
                tmpRow.CreateCell(1).SetCellValue(report[i].WorkOrderNo);
                tmpRow.CreateCell(2).SetCellValue(report[i].WorkshopName);
                tmpRow.CreateCell(3).SetCellValue(report[i].BarCode);
                tmpRow.CreateCell(4).SetCellValue(report[i].ProductName);
                tmpRow.CreateCell(5).SetCellValue((int)report[i].CurSite);
                tmpRow.CreateCell(6).SetCellValue(report[i].Reviewed);
                tmpRow.CreateCell(7).SetCellValue((double)report[i].ReviewedBy);
                tmpRow.CreateCell(8).SetCellValue(report[i].QLevel);
                tmpRow.CreateCell(9).SetCellValue(report[i].ReviewLevel);
                tmpRow.CreateCell(10).SetCellValue(report[i].DowngradeBadTypeName);
                tmpRow.CreateCell(11).SetCellValue(report[i].DowngradeBadName);
                tmpRow.CreateCell(12).SetCellValue(report[i].ReviewBadTypeName);
                tmpRow.CreateCell(13).SetCellValue(report[i].ReviewBadName);
                for (int j = 0; j <= 14; j++)
                {
                    tmpRow.GetCell(j).CellStyle = styleCenter;
                }
            }

            var ms = new MemoryStream();
            book.Write(ms);
            Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xlsx", $"降级复判（{startDate:yyyyMMddHHmm}-{endDate:yyyyMMddHHmm}）"));
            Response.BinaryWrite(ms.ToArray());
            book = null;
            ms.Close();
            ms.Dispose();
            return;
        }

        #endregion

        #region 锁定解锁
        /// <summary>
        /// 组件锁定管理
        /// </summary>
        public ActionResult LockMgr()
        {
            ViewBag.Workshops = new WorkshopMgr().QueryUserWorkshops(BaseEnv.UserId);
            ViewBag.ReviewStatusEnum = new CommonMgr().QueryEnumTypes(typeof(ReviewResult));
            return View();
        }

        /// <summary>
        /// 查询锁定列表
        /// </summary>
        [HttpPost]
        public JsonResult QueryLocks(int page, int limit, string workshopCode, string orderNo, string workOrderNo, string barCode,
            DateTime startDate, DateTime endDate, bool? reviewed)
        {
            var total = 0;
            var models = new LockMgr().QueryLocks(page, limit, out total, workshopCode, orderNo, workOrderNo, barCode, startDate, endDate.AddDays(1), reviewed);
            return Json(new ResultJson<object>(models, total));
        }

        /// <summary>
        /// 解锁
        /// </summary>
        [HttpPost]
        public JsonResult UnLock(string barCode, string unLockReason)
        {
            new LockMgr().UnLock(new List<string> { barCode }, 0, unLockReason, BaseEnv.UserId);
            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 批量锁定
        /// </summary>
        public ActionResult BatchLock()
        {
            ViewBag.SiteTypes = new CommonMgr().QueryEnumTypes(typeof(SiteType));
            return View();
        }

        /// <summary>
        /// 批量锁定
        /// </summary>
        [HttpPost]
        public JsonResult BatchLock(List<string> barCodes, SiteType curSite, SiteType lockSite, string lockReason)
        {
            new LockMgr().Lock(barCodes, curSite, lockSite, BaseEnv.UserId, lockReason);
            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 批量解锁
        /// </summary>
        public ActionResult BatchUnLock()
        {
            return View();
        }

        /// <summary>
        /// 解锁
        /// </summary>
        [HttpPost]
        public JsonResult BatchUnLock(List<string> codes, int type, string unLockReason)
        {
            new LockMgr().UnLock(codes, type, unLockReason, BaseEnv.UserId);
            return Json(new ResultJson<object>());
        }
        #endregion

        #region OBA检验
        /// <summary>
        /// OBA检验
        /// </summary>
        public ActionResult ObaMgr()
        {
            ViewBag.ObaStatusEnums = new CommonMgr().QueryEnumTypes(typeof(ObaStatus));
            return View();
        }

        /// <summary>
        /// 查询降级复判列表
        /// </summary>
        [HttpPost]
        public JsonResult QueryObas(int page, int limit, string orderNo, string obaNo, DateTime startDate, DateTime endDate, ObaStatus? status)
        {
            var total = 0;
            var models = new ObaMgr().QueryObas(page, limit, out total, orderNo, obaNo, status, startDate, endDate.AddDays(1));
            return Json(new ResultJson<object>(models, total));
        }

        /// <summary>
        /// 完结OBA
        /// </summary>
        [HttpPost]
        public JsonResult FinishOba(string obaNo)
        {
            new ObaMgr().FinishOba(new DataAccess.VModel.VObaInspect
            {
                ObaNo = obaNo,
                ModifyBy = BaseEnv.UserId
            });
            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// OBA包装清单
        /// </summary>
        public ActionResult ObaList(string obaNo)
        {
            ViewBag.ObaNo = obaNo;
            return View();
        }

        /// <summary>
        /// 查询降级复判列表
        /// </summary>
        [HttpPost]
        public JsonResult QueryObaPackss(string obaNo)
        {
            var obaPacks = new ObaMgr().QueryObaPacks(obaNo);
            return Json(new ResultJson<object>(obaPacks, obaPacks.Count));
        }
        #endregion

        #region 返修工单
        /// <summary>
        /// 返修工单管理
        /// </summary>
        public ActionResult ReworkMgr()
        {
            ViewBag.Workshops = new WorkshopMgr().QueryUserWorkshops(BaseEnv.UserId);
            ViewBag.ProcessStatusEnum = new CommonMgr().QueryEnumTypes(typeof(ProduceStatus));
            ViewBag.ReviewStatusEnum = new CommonMgr().QueryEnumTypes(typeof(ReviewStatus));
            ViewBag.ReworkTypes = new CommonMgr().QueryEnumTypes(typeof(ReworkType));

            return View();
        }

        /// <summary>
        /// 查询返修单列表
        /// </summary>
        [HttpPost]
        public JsonResult QueryReworks(int page, int limit, string orderNo, string reworkNo, string workshopCode, ReviewStatus? reviewStatus, ProduceStatus? produceStatus, ReworkType? reworkType, DateTime? startDate, DateTime? endDate)
        {
            var total = 0;
            var models = new ReworkMgr().QueryReworks(page, limit, out total, orderNo, reworkNo, workshopCode, reviewStatus, produceStatus, reworkType, startDate, endDate?.AddDays(1));
            return Json(new ResultJson<object>(models, total));
        }

        /// <summary>
        /// 返修单编辑
        /// </summary>
        public ActionResult ReworkEdit(string reworkNo)
        {
            ViewBag.Workshops = new WorkshopMgr().QueryUserWorkshops(BaseEnv.UserId);
            ViewBag.ReworkTypes = new CommonMgr().QueryEnumTypes(typeof(ReworkType));
            ViewBag.Sites = new CommonMgr().QueryEnumTypes(typeof(SiteType)).Where(_ => _.Key != 99).ToList();

            var rework = new ReworkMgr().GetRework(reworkNo);
            return View(rework);
        }

        /// <summary>
        /// 返修单编辑
        /// </summary>
        [HttpPost]
        public JsonResult SaveRework(VReworkOrder model)
        {
            if (string.IsNullOrWhiteSpace(model.ReworkNo))
            {
                model.CreateBy = BaseEnv.UserId;
            }
            else
            {
                model.ModifyBy = BaseEnv.UserId;
            }
            new ReworkMgr().SaveRework(model);
            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 选择站点弹窗
        /// </summary>
        public ActionResult SelectSite(SiteType site)
        {
            var siteItem = new CommonMgr().QueryEnumTypes(typeof(SiteType)).FirstOrDefault(_ => _.Key == (int)site);
            return View(siteItem);
        }

        /// <summary>
        /// 返修清单
        /// </summary>
        /// <returns></returns>
        public ActionResult ReworkItemList(string reworkNo)
        {
            ViewBag.ReworkNo = reworkNo;
            return View();
        }

        /// <summary>
        /// 获取返工单
        /// </summary>
        [HttpPost]
        public JsonResult GetRework(string reworkNo)
        {
            var model = new ReworkMgr().GetRework(reworkNo);
            return Json(new ResultJson<object>(model));
        }

        /// <summary>
        /// 添加返工对象
        /// </summary>
        [HttpPost]
        public JsonResult AddReworkItems(string reworkNo, List<string> itemNos)
        {
            new ReworkMgr().AddReworkItems(new VReworkOrder { ReworkNo = reworkNo, ModifyBy = BaseEnv.UserId },
                itemNos.Where(_ => !string.IsNullOrWhiteSpace(_)).Select(_ => _.ToUpper()).Distinct().Select(_ => new VReworkItem { ReworkItemNo = _ }).ToList());
            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 移除返工对象
        /// </summary>
        [HttpPost]
        public JsonResult RemoveReworkItem(string reworkNo, string itemNo)
        {
            new ReworkMgr().RemoveReworkItem(new VReworkItem { ReworkNo = reworkNo, ReworkItemNo = itemNo, ModifyBy = BaseEnv.UserId });
            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 提交审核
        /// </summary>
        [HttpPost]
        public JsonResult SubmitReview(string reworkNo)
        {
            new ReworkMgr().SubmitReview(new VReworkOrder { ReworkNo = reworkNo, ModifyBy = BaseEnv.UserId });
            return Json(new ResultJson<object>());
        }
        #endregion

        #region 解包解柜
        /// <summary>
        /// 解包管理
        /// </summary>
        /// <returns></returns>
        public ViewResult PackMgr()
        {
            ViewBag.PackStatusEnum = new CommonMgr().QueryEnumTypes(typeof(PackStatus));
            ViewBag.PackInspectStatusEnum = new CommonMgr().QueryEnumTypes(typeof(PackInboundInspectStatus));
            return View();
        }

        /// <summary>
        /// 打包详情
        /// </summary>
        /// <returns></returns>
        public ViewResult PackDetail(string packNo)
        {
            ViewBag.WorkShops = new WorkshopMgr().QueryUserWorkshops(BaseEnv.UserId);
            var pack = string.IsNullOrWhiteSpace(packNo) ? null : new WorkOrderMgr().GetPack(packNo);
            ViewBag.User = pack == null ? BaseEnv.User : new UserMgr().GetUser(pack.CreateBy);
            return View(pack);
        }

        /// <summary>
        /// 拼柜管理
        /// </summary>
        /// <returns></returns>
        public ViewResult CabinetMgr()
        {
            ViewBag.Warehouses = new WarehouseMgr().QueryUserWarehouses(BaseEnv.UserId);
            return View();
        }

        /// <summary>
        /// 拼柜详情
        /// </summary>
        /// <returns></returns>
        public ViewResult CabinetDetail(string cabinetNo)
        {
            var cabinet = string.IsNullOrWhiteSpace(cabinetNo) ? null : new CabinetMgr().GetCabinet(cabinetNo);
            return View(cabinet);
        }
        #endregion

        #region 手动降级
        /// <summary>
        /// 手动降级管理
        /// </summary>
        public ActionResult ManuallyDowngradeIndex()
        {
            ViewBag.Workshops = new WorkshopMgr().QueryUserWorkshops(BaseEnv.UserId);
            return View();
        }

        /// <summary>
        /// 查询手动降级记录
        /// </summary>
        [HttpPost]
        public JsonResult QueryManuallyDowngrades(int page, int limit, string workshopCode, DateTime startTime, DateTime endTime,
            string orderNo, string workOrderNo, string barCode)
        {
            var result = new ProductViaSiteMgr().QueryManuallyDowngrades(page, limit, workshopCode, startTime, endTime, orderNo, workOrderNo, barCode);
            return Json(new ResultJson<object>(result.Item2, result.Item1));
        }

        /// <summary>
        /// 手动降级
        /// </summary>
        public ActionResult ManuallyDowngrade()
        {
            var workshopCodes = new WorkshopMgr().QueryUserWorkshops(BaseEnv.UserId).Select(_ => _.WorkshopCode).ToList();
            ViewBag.Schemas = new BinningSchemeMgr().QueryAllSchemas(workshopCodes);
            return View();
        }

        /// <summary>
        /// 上传降级条码
        /// </summary>
        [HttpPost]
        public JsonResult UploadDowngradeCodes(List<string> barCodes)
        {
            barCodes = barCodes.Where(_ => !string.IsNullOrWhiteSpace(_)).Select(_ => _.ToUpper().Trim()).Distinct().ToList();
            var components = new ComponentMgr().QueryComponents("", "", barCodes);
            var unPackComponents = components.Where(_ => !string.IsNullOrWhiteSpace(_.PackNo)).Select(_ => _.BarCode).ToList();
            if (unPackComponents.Any())
            {
                return Json(new ResultJson<object>(1, $"下列组件未解包，请解包后再降级：{string.Join("、", unPackComponents)}"));
            }

            return Json(new ResultJson<object>(components.Select(_ => new VManuallyDowngradeRecord
            {
                WorkshopCode = _.WorkshopCode,
                WorkshopName = _.WorkshopName,
                OrderNo = _.OrderNo,
                WorkOrderNo = _.WorkOrderNo,
                BarCode = _.BarCode,
                OldPower = (int)_.IVPowerLevel,
                OldNameplateModel = _.NameplateModel,
                OldCurrent = _.IVCurrentLevel,
                NewPower = 0,
                NewCurrent = "",
                NewNameplateModel = "",
                FF = _.FF,
                Im = _.Im,
                Isc = _.Isc,
                Pmax = _.Pmax,
                Vm = _.Vm,
                Voc = _.Voc
            }).ToList()));
        }

        /// <summary>
        /// 执行手动降级
        /// </summary>
        [HttpPost]
        public JsonResult DoManuallyDowngrade(List<string> barCodes, int schemaId)
        {
            new ProductViaSiteMgr().ManuallyDowngrade(barCodes, schemaId, BaseEnv.UserId);
            return Json(new ResultJson<object>());
        }
        #endregion
    }
}
